package com.roc.web.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.OperatorAuth;
import com.roc.pojo.Operators;
import com.roc.service.ServiceException;
import com.roc.service.operator.OperatorReceiveService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/operatorAuth")
public class OperatorAuthAction extends PaginationBaseAction {
	
	

	/**
	 * 
	 */
	private static final long serialVersionUID = 7635674482684103845L;
	
	private Logger logger=LogManager.getLogger(OperatorAuthAction.class);
	
	private OperatorAuthSearchCondition searchCondition;
	private String OperatorAuthIdList;
	private String authIdList;
	
	@Autowired
	IPageService pageService;
	
	@Autowired
	private OperatorReceiveService operatorReceiveService;
	
	/**
	 * 跳转实名审核领件页面
	 * */
	@Action(value="toList",results={@Result(name=SUCCESS,location="/pages/operator/operatorAuthList.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String returnCollarPiecesJsp(){
		try {
			Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			 if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
				 addActionError("无权限访问");
				 return ERROR;
			 }
		} catch (Exception e) {
			logger.error("跳转实名审核领件页面出错");
		}
		return SUCCESS;
	}

	/**
	 * 查询领件
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryOperatorsAuth", 
			results = { @Result(name = "success", location = "/pages/operator/operatorAuthList.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String queryOperatorAuth() throws Exception{
       
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(!op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()) &&
					   !op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())	){
					addActionError("无此权限");
						return SUCCESS;
			}
			 if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
				 addActionError("无权限访问");
				 return ERROR;
			 }
			if (searchCondition == null) {
				searchCondition = (OperatorAuthSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new OperatorAuthSearchCondition();
				}
			}

			if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || 
			   op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())  ){
				handleResultListForCollarPieces(op);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
			return SUCCESS;
	}
	
	@Action(value="saveReceive")
	public String saveCollarPieces(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		PrintWriter pw = null;
		JSONObject json = new JSONObject();
		try {
			getResponse().setCharacterEncoding("utf-8");
			pw = getResponse().getWriter();
			logger.info(op.getRealName()+"开始领取云商宝会员实名认证,商户号是："+OperatorAuthIdList);
			List<String> rsList = operatorReceiveService.addReceiveInfo(op, authIdList);
			
			json.put("rsList", rsList);
			pw.write(json.toString());
						
		} catch (Exception e) {
			logger.error("领件异常");
			logger.error(e.getMessage(),e);
		}finally{
			if(pw != null){
				pw.close();
			}
		}
		
		return null;
	}
	
	/**
	 * 处理查询结果
	 * @throws Exception 
	 * @throws ServiceException 
	 * */
	private void handleResultListForCollarPieces(Operators  op) throws Exception {
		try {
			int rows = pageService.countSQL(searchCondition);
			List<OperatorAuth> msList = new ArrayList<OperatorAuth>();
			if (rows > 0) {
				searchRsList = pageService.findAllSQL(searchCondition, 
													calcuStart(getCurrentPage()),
													Constance.PAGE_MAX_SIZE);
				if(searchRsList!=null&&searchRsList.size()>0){
					msList = handleDetail(searchRsList);
				}
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute("COUNT", rows);//统计次数
			getRequest().setAttribute(SEARCH_RS_LIST, msList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new Exception("查询失败",e);
		}
	}
	
	private List<OperatorAuth> handleDetail(List<Object> objList) throws Exception{
		List<OperatorAuth> list = new ArrayList<OperatorAuth>();
		Iterator iterator = objList.iterator();
		while (iterator.hasNext()) {
			OperatorAuth operatorAuth = new OperatorAuth();
			Object[] obj = (Object[]) iterator.next();
			operatorAuth.setId(Long.parseLong(Constance.Null2EmptyTrim(obj[0])));
			operatorAuth.setAccountNo(Constance.Null2EmptyTrim(obj[1]));
			operatorAuth.setUserName(Constance.Null2EmptyTrim(obj[2]));
			operatorAuth.setCardType(Constance.Null2EmptyTrim(obj[3]));
			operatorAuth.setCardNo(Constance.Null2EmptyTrim(obj[4]));
			operatorAuth.setCreateAtStr(Constance.Null2EmptyTrim(obj[9]));
			operatorAuth.setExt1(Constance.Null2EmptyTrim(obj[10]));
			operatorAuth.setExt2(Constance.Null2EmptyTrim(obj[11]));
			list.add(operatorAuth);
		}
		return list;
		
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_OPERATOR_AUTH, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (OperatorAuthSearchCondition) getSession().getAttribute(SEARCH_SESSION_OPERATOR_AUTH);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}

	public OperatorAuthSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(OperatorAuthSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public String getOperatorAuthIdList() {
		return OperatorAuthIdList;
	}

	public void setOperatorAuthIdList(String operatorAuthIdList) {
		OperatorAuthIdList = operatorAuthIdList;
	}

	public OperatorReceiveService getOperatorReceiveService() {
		return operatorReceiveService;
	}

	public void setOperatorReceiveService(
			OperatorReceiveService operatorReceiveService) {
		this.operatorReceiveService = operatorReceiveService;
	}

	public String getAuthIdList() {
		return authIdList;
	}

	public void setAuthIdList(String authIdList) {
		this.authIdList = authIdList;
	}
	
	

}
